#include <iostream>
#include <unistd.h>
#define K 1024
#define WRITELEN K*128
using namespace std;
int main()
{
    int result = -1;
    int fd[2],nbytes;
    pid_t pid;
    char string[WRITELEN] = {"hello world"};
    char readbuffer[10*K];
    int *write_fd = &fd[1];
    int *read_fd = &fd[0];
    result = pipe(fd);
    if(-1==result)
    {
        cout<<"建立管道失败!"<<endl;
        return -1;
    }
    pid = fork();
    if(-1 == pid)
    {
        cout<<"fork进程失败\n";
        return -1;
    }
    else if(0 == pid)
    {
        int write_size = WRITELEN;
        result = 0;
        close(*read_fd);
        while(write_size>=0)
        {
            result = write(*write_fd,string,write_size);
            if(result>0)
            {
                write_size -= result;
                cout<<"写入数据个数："<<result<<"剩余数据:"<<write_size<<endl;
            }
            else
            {
                sleep(10);
            }
        }
        return 0;
    }
    else
    {
        close(*write_fd);
        while(1)
        {
            nbytes = read(*read_fd,readbuffer,sizeof(readbuffer));
            if(nbytes <= 0)
            {
                cout<<"没有数据写入了\n";
                break;
            }
            cout<<"接收到"<<nbytes<<"个数据，内容为："<<readbuffer<<"\n";
        }
    }
    return 0;
}
